const axios = require('axios');

let group = {};

/**
 * 创建分组
 * @param title
 * @param option
 */
group.create = function (title, option) {
    $.ajax({
        url : '/api/album/create.do',
        method : 'post',
        data : { title : title },
        dataType : 'JSON',
        success : function (result) {
            if(result.error === 0){
                if('success' in option)
                    option.success(result.data);
            } else {
                if('fail' in option)
                    option.fail(result.message);
            }
        },
        error : function () {
            if('error' in option)
                option.error();
        }
    });
};

group.list = function (option) {
    axios.get('/api/album/list.ajax').then(function (response) {
        if(response.data.error === 0){
            if('success' in option)
                option.success(response.data.data);
        } else {
            if('fail' in option)
                option.fail(response.data.message);
        }
    }).catch(function (error) {
        if('error' in option)
            option.error(error);
    });
};

let image = {};

image.list = function (id, page, option) {
    axios.get('/api/album/images.ajax',{ params: {
        id: id, page : page
    }}).then(function (response) {
        if(response.data.error === 0){
            if('success' in option)
                option.success(response.data.data);
        } else {
            if('fail' in option)
                option.fail(response.data.message);
        }
    }).catch(function (error) {
        if('error' in option)
            option.error(error);
    });
};


image.upload = function (file, album, option) {
    let data = new FormData();
    data.append('file', file);
    data.append('album', album);
    axios.post('/api/album/upload.do',data).then(function (response) {
        if(response.data.error === 0){
            if('success' in option)
                option.success(response.data.data);
        } else {
            if('fail' in option)
                option.fail(response.data.message);
        }
        if('complete' in option)
            option.complete();
    }).catch(function (error) {
        if('error' in option)
            option.error(error);
        if('complete' in option)
            option.complete();
    });
};

module.exports = {
    group : group,
    image : image
};